package com.tx.studentManager.common;


import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.tx.studentManager.model.UrlFilter;
import com.tx.studentManager.service.UrlFilterService;

/**
 * 
 * @描述 初始化载入权限访问链
 * @since studentManager-admin 1.0.2
 * @version 1.0 2015-9-28 上午10:06:21
 * @author 此生唯晴
 */
public class MyFilterChainDefinitionsLoader implements Runnable {

	@Autowired
	private UrlFilterService urlFilterService;
	private AbstractShiroFilter shiroFilter;
	
	private Logger logger=Logger.getLogger(MyFilterChainDefinitionsLoader.class);
	
	synchronized public void loadShiroFilterMap(){
		logger.info("------------加载访问资源和权限------------");
		PathMatchingFilterChainResolver filterChainResolver=(PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
		logger.info(filterChainResolver);
		DefaultFilterChainManager filterChainManager=(DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
		logger.debug(filterChainManager);
		List<UrlFilter> urlFilters=urlFilterService.findAll();
		for (UrlFilter urlFilter : urlFilters) {
			String url=urlFilter.getUrl();
			url=(url.indexOf("?")>0)?url.substring(0,url.indexOf("?")):url;
			filterChainManager.createChain(url, "authc,perms["+url+"]");
		}
	}
	
	
	public AbstractShiroFilter getShiroFilter() {
		return shiroFilter;
	}

	public void setShiroFilter(AbstractShiroFilter shiroFilter) {
		this.shiroFilter = shiroFilter;
	}

	@Override
	public void run() {
		loadShiroFilterMap();
	}

	public void initLoad(){
		Thread thread =new Thread(this);
		thread.start();
	}
}
